package cn.chainco.cts.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import cn.chainco.cts.iservice.CommonManager;
import cn.chainco.cts.iservice.IEmployeeManager;
import cn.chainco.cts.iservice.IUserManager;
import cn.chainco.cts.jdo.Company;
import cn.chainco.cts.jdo.Employee;
import cn.chainco.cts.jdo.User;
import cn.chainco.cts.jdo.Work;
import cn.chainco.cts.utils.CommUtils;
import cn.chainco.cts.utils.CookieUtil;
import cn.chainco.cts.utils.MD5;
import cn.chainco.cts.utils.MyMailSender;
import cn.chainco.cts.utils.TimeUtil;
import cn.chainco.cts.utils.VarData;
import cn.chainco.cts.utils.query.OP;
import cn.chainco.cts.utils.query.Page;
import cn.chainco.cts.utils.query.QueryOrder;
import cn.chainco.cts.utils.query.QueryParam;

import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
@InterceptorRef("ctsInterceptors")
public class EmployeeAction extends ActionSupport{
	private CommonManager commonManager;
	private IEmployeeManager employeeManager;
	private List<Employee> employeeList;
	private Employee employee;
	private String keyword;
	private int pageSize=15;
	private int pageNumber=1;
	private Page pager;
	private IUserManager userManager;
	
	/**
	 * 查询公司所有员工
	 * @return
	 */
	@Action("findEmployee")
	public String findEmployee(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String companyId = CookieUtil.getCookieValue(ServletActionContext.getRequest(), "cts_emplcpyid");
		String type = request.getParameter("type");
		String searchtype = request.getParameter("searchtype");
		String searchstatus = request.getParameter("searchstatus");
		
		try {
			if(CommUtils.isCorrectNumber(companyId)){
				if(type == null || type == ""){
					type = "0"; // 0.员工，1访客
				}
				
				Company company = this.commonManager.findEntityByPK(Company.class, Long.valueOf(companyId));
				List<Employee> empllist = this.employeeManager.findEmployee(company , type , keyword , searchstatus ,  null , null);
				for (Employee employee : empllist) {
					if(employee.getUser()!=null && employee.getUser().getId()!=0){
						User user = this.commonManager.findEntityByPK(User.class, employee.getUser().getId());
						employee.setUser(user);
					}
				}
				
				empllist = getPageList(empllist, request);
				request.setAttribute("company", company);
				request.setAttribute("searchstatus", searchstatus);
				request.setAttribute("searchtype", searchtype);
				request.setAttribute("employeelist", empllist);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		String employeeId = CookieUtil.getCookieValue(request, "cts_employeecpyid");
		Employee employee = this.commonManager.findEntityByPK(Employee.class , Long.valueOf(employeeId));
		request.setAttribute("employee", employee);
		if(employee==null || (employee.getAuth5()!=1 && type.equals("1")) || (employee.getType()!=2 && type.equals("0"))){
			request.setAttribute("type", "");
		}else{
			request.setAttribute("type", type);
		}
		request.setAttribute("isEmp", 1);
		 return "/company/mainMeun";
		//return "/company/companyParamList";
	}
	
	public <E>List<E> getPageList(List<E> list , HttpServletRequest request){
		pager = new Page();
		pager.setElements(list);
		pager.setPageNumber(pageNumber);
		pager.setPageSize(pageSize);
		pager.setTotalElements(list.size());
	   
		request.setAttribute("pageCount", pager.getLastPageNumber());
	    return pager.getCurrentElements();
	}
	
	/**
	 * 显示单条员工信息
	 * @return
	 */
	@Action("findSingleEmployee")
	public String findSingleEmployee(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String id = request.getParameter("id");
		String companyId = CookieUtil.getCookieValue(ServletActionContext.getRequest(), "cts_emplcpyid");
		String type = request.getParameter("type");
		String noplay = request.getParameter("noplay");
		String isUpUser = request.getParameter("isUpUser");
		
		if(CommUtils.isCorrectNumber(id)){
			employee = this.commonManager.findEntityByPK(Employee.class, Long.valueOf(id));
		}else{
			employee = new Employee();
		}
		
		Long codePrefix = System.currentTimeMillis(); // 邀请码
		String vcode = MD5.toMD5(codePrefix.toString());
		Company company = this.commonManager.findEntityByPK(Company.class, Long.valueOf(companyId));
		
		request.setAttribute("code", vcode);
		request.setAttribute("company", company);
		request.setAttribute("type", type);
		request.setAttribute("noplay", noplay);
		request.setAttribute("isUpUser", isUpUser);
		
		return "/company/addEmployee";
	}
	
	
	/**
	 * 添加员工
	 *
	 */
	@Action("saveEmployee")
	public void saveEmployee(){
		@SuppressWarnings("unused")
		HttpServletRequest request = ServletActionContext.getRequest();
		String toUrl = request.getParameter("toUrl");
		
		String employeeId = request.getParameter("employeeId");
		String userId = request.getParameter("userId");
		String userName = request.getParameter("userName");
		String ntcpyId = request.getParameter("ntcpyId"); 
		String isUpUser = request.getParameter("isUpUser");
		
		String companyId = CookieUtil.getCookieValue(ServletActionContext.getRequest(), "cts_emplcpyid");
		// 是否在他人的公司
		if(ntcpyId!=null && ntcpyId.equals("1")){
			companyId = ntcpyId;
		}
		
		User user = null;
		
		int code = 0;
		try {
			if(employee!=null && CommUtils.isCorrectNumber(companyId)){
				Company company = this.commonManager.findEntityByPK(Company.class, Long.valueOf(companyId));
				
				boolean isNew = false;
				if(userName!=null && !"".equals(userName)){
					List<QueryParam> paramList = new ArrayList<QueryParam>();
					QueryParam param = new QueryParam();
					param.setField("userName");
					param.setOp(OP.equal);
					param.setValue(new Object[]{userName});
					paramList.add(param);
					List<User> _userlist = this.commonManager.findByCustomized(User.class, paramList, null);
					if(_userlist==null || _userlist.size()==0){ // 创建用户
						  user = new User();
						  user.setStatus(2);
						  user.setCreateTime(new Date());
						  user.setUserName(userName);
						  user.setUserPass(MD5.toMD5("123456"));
						  Long __userId = this.commonManager.saveEntity(user);
						  user.setId(__userId);
						  isNew = true;
					}else{
						  user = _userlist.get(0);
					}
				}
				
				
				Long result = 0L ;  
				if(CommUtils.isCorrectNumber(employeeId) && !"0".equals(employeeId)){ // 更新
					// 验证用户名称d
					employee.setUser(user);
					employee.setCompany(company);
					employee.setId(Long.valueOf(employeeId));
					this.commonManager.modifyEntity(employee);
					result = Long.valueOf(employeeId);
				}else{// 邀请
					 employee.setUser(user);
					 employee.setCompany(company);		    
					 employee.setCreateTime(new Date());
					 result = this.commonManager.saveEntity(employee);
				}
				
				if(employee.getUser()!=null){
				  if(result > 0){
					Employee modfEmployee = this.commonManager.findEntityByPK(Employee.class, result);
					if(modfEmployee.getInvite() == 0){
						try {
							if(employee.getUser()!=null && employee.getUser().getId()!=0){
								
								Long codePrefix = System.currentTimeMillis(); // 邀请码
								String vcode = MD5.toMD5(codePrefix.toString());
								modfEmployee.setInvite(1);
								modfEmployee.setInviteCode(vcode);
								this.commonManager.modifyEntity(modfEmployee);
								employee = modfEmployee;
								
								String mail = employee.getUser().getUserName(); // 邮件地址
								sendMail(employee , mail , isNew , toUrl);
							}
							
							code = Integer.valueOf(result+"");
							
						} catch (Exception e) {
							if(employeeId == null || employeeId.equals("") || employeeId.equals("0")){
								this.commonManager.deleteEntityByPK(Employee.class, result);
							}else{
								Employee em = this.commonManager.findEntityByPK(Employee.class, result);
								em.setUser(null);
								em.setInvite(0);
								em.setInviteCode(null);
								this.commonManager.modifyEntity(em);
							}
							code = 0;
							e.printStackTrace();
						}
					}else{
						code = Integer.valueOf(result+"");
					}
					
				 }
			   }else{
				   code = Integer.valueOf(result+"");
			   }
			}
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
		
		ActionUtil.outputData(code);
		
		
	}
	
	/**
	 * 取消邀请
	 *
	 */
	@Action("cancelInvited")
	public void cancelInvited(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String id = request.getParameter("id");
		int code = 0;
		
		if(CommUtils.isCorrectInt(id)){
			Employee employee_0 = this.commonManager.findEntityByPK(Employee.class, Long.valueOf(id));
			employee_0.setUser(null);
			employee_0.setInvite(0);
			this.commonManager.modifyEntity(employee_0);
		    code = 1;
		}
		
		ActionUtil.outputData(code);
	}

	
	/**
	 * 验证成员名称是否重复
	 */
	@Action("vailEmpNickName")
	public void vailEmpNickName(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String nickName = request.getParameter("nickname");
		String findType = request.getParameter("findtype");
		String userId = request.getParameter("userid");
		String id = request.getParameter("id");
		
		String companyId = CookieUtil.getCookieValue(request, "cts_emplcpyid");
		
		int code = 0;
		
		if(findType !=null && !findType.equals("")){
			if(nickName!=null && !"".equals(nickName) && CommUtils.isCorrectNumber(companyId)){
				String sql = "";
				
				if("0".equals(findType)){ // 是否已存在的成员
					sql = " 1=1 and nickname='"+nickName+"' and companyId='"+companyId+"'";
					List<Employee> empllist = ActionUtil.findListByE(Employee.class, sql);
					
					if(empllist!=null && empllist.size() > 0){
						Employee _employee = empllist.get(0);
						if(id==null || "".equals(id) || _employee.getId()!=Long.valueOf(id)){
							code = 1;
						}
					}

				}else if("1".equals(findType)){// 邀请用户是否已存在
					sql = " 1=1 and userId='"+userId+"' and companyId='"+companyId+"'";
					List<Employee> empllist = ActionUtil.findListByE(Employee.class, sql);
					code = (empllist!=null && empllist.size() > 0) ? 2 : 0;
				}else if("3".equals(findType)){
					// 是否已是员工
					sql = " 1=1 and nickname='"+nickName+"' and companyId='"+companyId+"'";
					List<Employee> empllist = ActionUtil.findListByE(Employee.class, sql);
					if(empllist!=null && empllist.size() > 0){
						Employee _employee = empllist.get(0);
						if(id==null || "".equals(id) || _employee.getId()!=Long.valueOf(id)){
							code = 1;
						}
					}
					
					// 是否这个cts用户已是公司的成员
					sql = " 1=1 and userId='"+userId+"' and companyId='"+companyId+"'";
					List<Employee> empllist2 = ActionUtil.findListByE(Employee.class, sql);
					if(empllist2!=null && empllist2.size() > 0){
					   Employee employeeType = 	empllist2.get(0);
					   if(id==null || "".equals(id) || employeeType.getId()!=Long.valueOf(id)){
						   code = employeeType.getType() == 0 ? 2 : 3; // 2.员工,3.访客
					   }
					}
					
					
				}
				
			}
		}
	  	
	  	ActionUtil.outputData(code);
	}
	
	/**
	 * 删除员工
	 *
	 */
	@Action("delEmployee")
	public void delEmployee(){
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			String empId = request.getParameter("id");
			if(CommUtils.isCorrectNumber(empId)){
                String companyId = CookieUtil.getCookieValue(request, "cts_emplcpyid");
				Employee employee = this.commonManager.findEntityByPK(Employee.class, Long.valueOf(empId));
				List<Employee> __emplist = this.employeeManager.findEmployeByUser(employee.getUser(), null);
				
				String sql = " 1=1 and (employeeId="+employee.getId() 
				           + " or client1="+employee.getId() 
				           + " or client2="+employee.getId()
				           + " or releaseCargoAgent1="+employee.getId()
				           + " or releaseCargoAgent2="+employee.getId()
				           + " or bookingAgentId="+employee.getId()
				           + " or expressAgentId1="+employee.getId()
				           + " or expressAgentId2="+employee.getId()
				           + " or truckingAgentId="+employee.getId()
				           + ")"
				           + " and companyId="+companyId;
				
				List<Work> worklist = ActionUtil.findListByE(Work.class, sql);
				
				if(worklist.size() <=0){
					if(__emplist.size()==1){ // 删除临时用户(只被当前引用)
						User __user = this.commonManager.findEntityByPK(User.class, employee.getUser().getId());
						if(__user.getStatus() == 2){
							this.commonManager.deleteEntity(__user);
						}
					}
					
					this.commonManager.deleteEntity(employee);
					ActionUtil.outputData("1");
				}else{
					ActionUtil.outputData("-1");
				}
					
			}else{
				ActionUtil.outputData("0");
			}
		} catch (NumberFormatException e) {
			ActionUtil.outputData("0");
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 到加入公司页面
	 * @return
	 */
	@Action("toCodeToAdd")
	public String toCodeToAdd(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String userId = request.getParameter("ukey"); // 用户id
		String employeeId = request.getParameter("ekey"); // 员工id
		String invitedCode = request.getParameter("workcode");
		String wtype = request.getParameter("wtype");
		
		if(CommUtils.isCorrectNumber(userId) && CommUtils.isCorrectNumber(employeeId)){
			User user = this.commonManager.findEntityByPK(User.class, Long.valueOf(userId));
			
			request.setAttribute("userStatus", user.getStatus());
			request.setAttribute("userId", userId);
			request.setAttribute("userName", user.getUserName());
			request.setAttribute("employeeId", employeeId);
			request.setAttribute("invitedCode", invitedCode);
			request.setAttribute("wtype", wtype);
			if(employeeId!=null && !"".equals(employeeId.trim())){
				Employee toEmployee = this.commonManager.findEntityByPK(Employee.class, Long.valueOf(employeeId));
				Company toCompany = this.commonManager.findEntityByPK(Company.class, toEmployee.getCompany().getId());
				request.setAttribute("tocompany", toCompany);
			}
		}
		
		request.setAttribute("invited", 1);
		request.setAttribute("place", 1);
		return "index";
	}
	
	/**
	 * 
	 *加入公司
	 */
	@Action("angainAdd")
	public void angainAdd(){
		HttpServletRequest request = ServletActionContext.getRequest();
		
		String userId = request.getParameter("userId");
		String employeeId = request.getParameter("employeeId"); 
		
		String pwd = request.getParameter("pwd"); // 密码
		String name = request.getParameter("name");
		String inviteCode = request.getParameter("inviteCode"); // 邀请码
		String wtype = request.getParameter("wtype");
		
		int code = 0;
		if(CommUtils.isCorrectNumber(userId) && CommUtils.isCorrectNumber(employeeId)){
			if(inviteCode == null || inviteCode.trim() == ""){
				code = -1; //邀请码不存在
			}else{
				User user = null;
				
				if(wtype!=null && wtype.equals("2")){
					try {
						List<QueryParam> paramList = new ArrayList<QueryParam>();
						QueryParam param = new QueryParam();
						param.setField("userName");
						param.setOp(OP.equal);
						param.setValue(new Object[]{name});
						paramList.add(param);
						
						QueryParam param1 = new QueryParam();
						param1.setField("userPass");
						param1.setOp(OP.equal);
						param1.setValue(new Object[]{MD5.toMD5(pwd)});
						paramList.add(param1);
						
						List<User> _userlist_ = this.commonManager.findByCustomized(User.class, paramList, null);
						
						if(_userlist_.size() > 0)
							user = _userlist_.get(0);
					} catch (RuntimeException e) {
						e.printStackTrace();
					}
				}else{
					user = this.commonManager.findEntityByPK(User.class, Long.valueOf(userId));
				}
				
				if(user == null){
					code = -2;
				}else{
					if(user.getStatus() == 2){
						user.setUserPass(MD5.toMD5(pwd));
						user.setStatus(0);
						this.commonManager.modifyEntity(user);
					}
					
					Employee employee = this.commonManager.findEntityByPK(Employee.class, Long.valueOf(employeeId));
					if(employee!=null){
						if(employee.getInviteCode().equals(inviteCode)  && employee.getInvite() == 1){
							employee.setInvite(2);
							employee.setInviteCode("");
							this.commonManager.modifyEntity(employee);
							code = Integer.valueOf(user.getId()+"");
						}else if(employee.getInvite() == 2){
						  code = -3;
						}else{
							code = -1;
						}
					}else{
						code = -1; //邀请码不存在
					}
				}
			}
		}else{
			code = -1;
		}
		
		ActionUtil.outputData(code);
	}
	
	/**
	 * 保存选中员工到cookie
	 *
	 */
	@Action("saveSelectEmployee")
	public void saveSelectEmployee(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String employeeId = request.getParameter("id");
		if(CommUtils.isCorrectNumber(employeeId)){
			int times = 0;
			if(CookieUtil.getCookieValue(request, "cts_times")!=""){
				times = Integer.valueOf(CookieUtil.getCookieValue(request, "cts_times"));
			}
			
			Employee emp = this.commonManager.findEntityByPK(Employee.class, Long.valueOf(employeeId));
			CookieUtil.addCookie(ServletActionContext.getResponse(), "cts_employeecpyid", employeeId  , "/", times);
			CookieUtil.addCookie(ServletActionContext.getResponse(), "cts_emplcpyid", emp.getCompany().getId() +"" , "/", times);
			CookieUtil.addCookie(ServletActionContext.getResponse(), "cts_emplcpytype", emp.getType() +"" , "/", times);
		    
			if(emp.getCompany()!=null){
				Company _company_ = this.commonManager.findEntityByPK(Company.class, emp.getCompany().getId());
				if(_company_.getStatus()!=1){
					new ActionUtil().clearEmployeeByCookie();
				}
			}
		}else{
			ActionUtil.outputData("0");
		}
	}
	
	/**
	 * 
	 * 发送邀请邮件
	 * @param type:是否要创建新用户(1是,0否)
	 * @throws Exception 
	 */
	private void sendMail(Employee employee , String tomail ,  boolean iscreate , String toUrl) throws Exception{
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		// 不要页面缓存
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);

		String sendTime = TimeUtil.getYYYY_MM_DDHHMM(new Date());
		String fromEmail = VarData.fromEmail;
		String emailPassword = VarData.emailPassword;
		String email = tomail;
		
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
		
		String content = "";
		String url = basePath + "toCodeToAdd?ekey="+employee.getId();
		url += "&ukey="+employee.getUser().getId();
		url += "&workcode="+employee.getInviteCode();
		
		if(iscreate == true){
			url+="&wtype=1";
			content = "您好！"+employee.getCompany().getName()+"公司邀请您使用全球货物跟踪系统，如果您同意请点击  <a href='"+url+"'>链接</a> 并用此邮箱注册后即可使用。";
		}else{
			url+="&wtype=2";
			content = "您好！"+employee.getCompany().getName()+"公司邀请您使用全球货物跟踪系统，如果您同意请点击  <a href='"+url+"'>链接</a> 登录即可使用。";
		}
		content += "<br/><a href="+url+">"+url+"</a>";
		content += "<br/>发送时间:" + sendTime;
		
		MyMailSender.sendMail(fromEmail , emailPassword, email, "邀请", "邀请" , content);
		ActionUtil.outputData(employee.getId());
	}
	
	/**
	 * 模糊查询员工
	 */
	@SuppressWarnings("unchecked")
	@Action("searchEmployeeBykeyword")
	public String searchEmployeeBykeyword(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String type = request.getParameter("type");
		Employee employee = ActionUtil.getSelectEmployee();
		List<QueryParam> queryList = new ArrayList<QueryParam>();
		QueryParam param = new QueryParam();
		param.setField(" nickname like '%"+keyword+"%' and status = 1 and companyId = " + employee.getCompany().getId());
		if("0".equals(type)){
			param.setField(param.getField() + " and type <> 1 ");
		}else if("1".equals(type)){
			param.setField(param.getField() + " and type = 1 ");
		}else if("all".equals(type)){
			
		}
		param.setOp(OP.sql);
		param.setValue(new Object[]{});
		queryList.add(param);
		if(pageSize == 0){
			pageSize = 10;
		}
		if(pageNumber == 0){
			pageNumber = 1;
		}
		List<QueryOrder> queryOrder = new ArrayList<QueryOrder>();
		QueryOrder order = new QueryOrder();
		order.setField("nickname");
		order.setAscOrder(true);
		queryOrder.add(order);
		try {
			pager = this.commonManager.findPageByCustomized(pageNumber, pageSize, Employee.class, queryList, queryOrder);
			employeeList = pager.getCurrentPageElements();
		} catch (RuntimeException e1) {
			employeeList = new ArrayList<Employee>();
		}
		
		Document document = DocumentHelper.createDocument();
		document.setXMLEncoding("UTF-8");
		Element rootElement = document.addElement("root");
		Element countNode = rootElement.addElement("count");
		countNode.addAttribute("count", "1");
		if(employeeList != null && employeeList.size() > 0){
			for(Employee obj: employeeList){
				Element searchObjNode = rootElement.addElement("searchObj");
				String value = obj.getNickname();
				if(value.indexOf("'") == -1){
					searchObjNode.addAttribute("value", value);
				}else{
					value = value.replaceAll("/'", "&acute;");
					searchObjNode.addAttribute("value", value);
				}
				searchObjNode.addAttribute("key", String.valueOf(obj.getId()));
				searchObjNode.addAttribute("type", "");
			}
		}

		String outPutStr = document.asXML();
		try{
			Pattern pattern = Pattern.compile("\\([0-9]{4,10}\\)|\\*");
			Matcher m = pattern.matcher(outPutStr);
			outPutStr = m.replaceAll("");
		}catch(Exception e){

		}
		ActionUtil.outputData(outPutStr);
		return null;
	}

	public CommonManager getCommonManager() {
		return commonManager;
	}

	public void setCommonManager(CommonManager commonManager) {
		this.commonManager = commonManager;
	}


	public IEmployeeManager getEmployeeManager() {
		return employeeManager;
	}

	public void setEmployeeManager(IEmployeeManager employeeManager) {
		this.employeeManager = employeeManager;
	}

	public Employee getEmployee() {
		return employee;
	}

	public void setEmployee(Employee employee) {
		this.employee = employee;
	}

	public String getKeyword(){
		return keyword;
	}

	public void setKeyword(String keyword){
		this.keyword = keyword;
	}

	public int getPageNumber(){
		return pageNumber;
	}

	public void setPageNumber(int pageNumber){
		this.pageNumber = pageNumber;
	}

	public Page getPager(){
		return pager;
	}

	public void setPager(Page pager){
		this.pager = pager;
	}

	public int getPageSize(){
		return pageSize;
	}

	public void setPageSize(int pageSize){
		this.pageSize = pageSize;
	}

	public List<Employee> getEmployeeList(){
		return employeeList;
	}

	public void setEmployeeList(List<Employee> employeeList){
		this.employeeList = employeeList;
	}
	
	
}
